package com.mgface.thymeleaf.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.mgface.thymeleaf.entity.UserInfo;
import com.mgface.thymeleaf.exception.ThymeleafSQLException;

@Repository("userInfoDao")
public class UserInfoDaoImpl implements UserInfoDao {
	@Autowired
	private DataSource dataSource;

	@Override
	public List<UserInfo> showUserInfo() {
		List<UserInfo> list = new ArrayList<>();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try{
			conn = dataSource.getConnection();
			//conn.setAutoCommit(false);//开启事务
			String sql = "select id,name,password from thymeleaf_userinfo";
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while(rs.next()){
				UserInfo ui = new UserInfo();
				ui.setU_id(rs.getString(1));
				ui.setU_name(rs.getString("name"));
				ui.setU_password(rs.getString(3));
				list.add(ui);
			}
			//conn.commit();//提交事务
		}catch(Exception e){
			throw new ThymeleafSQLException(2000, "数据库操作异常:"+e.getMessage()).set("~~看看还有什么说明的没有~~");
		}finally{
			if(rs!=null){
				try {
					rs.close();
				} catch (SQLException e) {
					throw new ThymeleafSQLException(2002, "RS关闭异常:"+e.getMessage());
				}
			}
			if(ps!=null){
				try {
					ps.close();
				} catch (SQLException e) {
					throw new ThymeleafSQLException(2003, "ps关闭异常:"+e.getMessage());
				}
			}
			if(conn!=null){
				try {
					conn.close();
				} catch (SQLException e) {
					throw new ThymeleafSQLException(2004, "conn关闭异常:"+e.getMessage());
				}
			}
		}
		return list;
	}

}
